<!-- eslint-disable ts/no-use-before-define -->
<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import OfflinePayModal from './OfflinePayModal.vue'
import { StudentApi } from '@/apis'
import { EnrollmentApi, OrderApi } from '@/apis'
import type { TableInstanceColumns } from '@/components/ProTable/type'
import type ProTable from '@/components/ProTable/index.vue'
import getAvatar from '@/utils/avatar'
import { formatMoney } from '@/utils/common'
import { useDictLabel, useForm } from '@/hooks'

defineOptions({
  name: 'DataDetail',
})

const router = useRouter()
const route = useRoute()

const loading = ref(false)

const initOrderPriceDetail = () => {
  return {
    originalTotalPrice: 0,
    actualTotalPrice: 0,
    discountTotalPrice: 0,
    couponDiscountPrice: 0,
    packageDiscountPrice: 0,
    otherDiscountPrice: 0,
  }
}
// 订单信息
const dataDetail = ref<OrderApi.OrderDetailResp>()
const orderPriceDetail = ref<OrderApi.OrderPriceDetail>(initOrderPriceDetail())

const getDataDetail = async (id) => {
  loading.value = true
  try {
    dataDetail.value = await OrderApi.getOrderDetail(id)
    studentInfo.value = await StudentApi.getStudentDetail(dataDetail.value.studentId)
    orderPriceDetail.value = {
      originalTotalPrice: dataDetail.value.originalTotalPrice,
      actualTotalPrice: dataDetail.value.actualTotalPrice,
      discountTotalPrice: dataDetail.value.discountDetail['优惠总额'],
      couponDiscountPrice: dataDetail.value.discountDetail['优惠券优惠'],
      packageDiscountPrice: dataDetail.value.discountDetail['联报优惠'],
      otherDiscountPrice: dataDetail.value.discountDetail['其它优惠'],
    }
  } finally {
    loading.value = false
  }
}

// 学生信息
const studentInfo = ref<StudentApi.StudentDetailResp>()

// 班级信息
const TableRef = ref<InstanceType<typeof ProTable>>()
const columns: TableInstanceColumns[] = [
  { title: '班级', slotName: 'className', fixed: 'left', width: 350 },
  { title: '课单价', dataIndex: 'actualUnitPrice', render: ({ record }) => formatMoney(record.actualUnitPrice) },
  { title: '总价', dataIndex: 'actualTotalPrice', render: ({ record }) => formatMoney(record.actualTotalPrice) },
  { title: '购课', slotName: 'lessonIndexes' },
  { title: '报名信息', slotName: 'enrollment' },
]
// 查看报名详情
const openEnrollment = (record) => {
  EnrollmentApi.getEnrollmentId({ studentId: record.studentId, classId: record.classId }).then((res) => {
    if (!res) {
      Message.warning('报名信息不存在，请确认是否支付')
    } else {
      router.push({ path: '/education/class/enroll/detail', query: { id: res } })
    }
  })
}

// 基础信息
const editing = ref(false)
const onCancelEditing = () => {
  editing.value = false
}
const onOpenEditing = () => {
  editing.value = true
}
const onUpdateEditing = () => {
  editing.value = false
}
const form = useForm({
  sellerId: undefined,
})

// 线下支付
const OfflinePayModalRef = ref<InstanceType<typeof OfflinePayModal>>()
const onOfflinePay = () => {
  OfflinePayModalRef.value?.open(dataDetail.value)
}
const onOfflinePaySuccess = async () => {
  await getDataDetail(dataDetail.value!.id)
}
// 刷新支付结果
const refreshLoading = ref(false)
const refreshPayResult = async () => {
  try {
    refreshLoading.value = true
    await OrderApi.refreshPayResult(dataDetail.value!.id)
    await getDataDetail(dataDetail.value!.id)
  } finally {
    refreshLoading.value = false
  }
}

watchEffect(() => {
  if (route.query.id) {
    getDataDetail(route.query.id)
  }
})
</script>

<template>
  <ProPage>
    <template #title>
      <a-page-header title="订单详情" @back="router.back()">
        <template #subtitle>
          <a-typography-text type="secondary" copyable>
            {{ dataDetail?.id }}
          </a-typography-text>
        </template>
      </a-page-header>
    </template>

    <a-card title="报名学生" class="section">
      <div class="flex gap-4">
        <a-avatar :size="54" shape="circle">
          <img :src="getAvatar(studentInfo?.avatar, studentInfo?.gender)" alt="avatar">
        </a-avatar>
        <div v-if="studentInfo">
          <div class="mb-3">
            <span class="font-size-16px font-600">{{ studentInfo.name }}</span>
            <CellGenderIcon :gender="studentInfo.gender" />
          </div>
          <CellDict :value="studentInfo.enrollStatus" code="EnrollStatusEnum" />
        </div>
        <div class="ml-6 flex-1">
          <a-row>
            <a-col :span="8">
              <span class="label">联系方式</span>
              <span class="value">{{ studentInfo?.parentPhone }}</span>
            </a-col>
            <a-col :span="8">
              <span class="label">出生年月</span>
              <span class="value">{{ studentInfo?.birthdate || '-' }}</span>
            </a-col>
            <a-col :span="8">
              <span class="label">入学年份</span>
              <span class="value">{{ studentInfo?.admissionYear || '-' }}</span>
            </a-col>
          </a-row>
          <a-row class="mt-4">
            <a-col :span="8">
              <span class="label">就读学校</span>
              <span class="value">{{ studentInfo?.fulltimeSchool || '-' }}</span>
            </a-col>
            <a-col :span="8">
              <span class="label">加入时间</span>
              <span class="value">{{ studentInfo?.createTime || '-' }}</span>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>
    <a-card title="报名班级" class="section">
      <ProTable
        ref="TableRef"
        :show-index="true"
        :data="dataDetail?.orderItemList"
        :columns="columns"
        :loading="loading"
        :pagination="false"
      >
        <template #className="{ record }">
          <CellClassInfo :id="record.classId" :name="record.className" />
        </template>
        <template #lessonIndexes="{ record }">
          <a-trigger position="top" auto-fit-position>
            <a-typography-text type="primary" class="cursor-pointer">
              {{ record.lessonIndexes.length }}节课
            </a-typography-text>
            <template #content>
              <div class="tooltip-content">
                第{{ record.lessonIndexes.join('、') }}节课
              </div>
            </template>
          </a-trigger>
        </template>
        <template #enrollment="{ record }">
          <a-button v-permission="['shop:order:manage']" type="text" @click="openEnrollment(record)">
            查看
          </a-button>
        </template>
      </ProTable>
    </a-card>
    <a-card title="订单信息" class="section">
      <div class="order-info flex-row-between-start">
        <a-space direction="vertical">
          <div class="text-16px text-black font-600">
            基础信息
            <a-space v-if="editing" size="mini">
              <a-button v-permission="['shop:order:manage']" size="mini" class="px-4px!" type="text" @click="onUpdateEditing">
                保存
              </a-button>
              <a-button v-permission="['shop:order:manage']" size="mini" class="px-4px!" type="text" @click="onCancelEditing">
                取消
              </a-button>
            </a-space>
            <a-button v-else size="mini" class="px-4px!" type="text" @click="onOpenEditing">
              <icon-edit />
            </a-button>
          </div>
          <div class="flex-row-start-center">
            <span class="item-label">家长备注</span>
            <span class="item-value">{{ dataDetail?.outRemark || '-' }}</span>
          </div>

          <div class="flex-row-start-center">
            <span class="item-label">内部备注</span>
            <a-textarea v-if="editing" v-model.trim="form.remark" placeholder="仅限员工内部查看" :max-length="255" show-word-limit />
            <span v-else class="item-value">{{ dataDetail?.remark || '-' }}</span>
          </div>
        </a-space>

        <a-space direction="vertical">
          <div class="text-16px text-black font-600">
            费用信息
          </div>
          <div class="flex-row-start-center">
            <span class="item-label">原价</span>
            <span class="item-value text-align-right color-[#4E5969]">{{ formatMoney(orderPriceDetail.originalTotalPrice) }}</span>
          </div>
          <div class="flex-row-start-center">
            <span class="item-label">优惠（用券）</span>
            <span class="item-value text-align-right color-[#FF7D00]">-{{ formatMoney(orderPriceDetail.couponDiscountPrice) }}</span>
          </div>
          <div class="flex-row-start-center">
            <span class="item-label">优惠（其它）</span>
            <span class="item-value text-align-right color-[#FF7D00]">-{{ formatMoney(orderPriceDetail.otherDiscountPrice) }}</span>
          </div>
          <div class="flex-row-start-center">
            <span class="item-label">应付</span>
            <span class="item-value text-align-right">{{ formatMoney(orderPriceDetail.actualTotalPrice) }}</span>
          </div>
        </a-space>

        <a-space direction="vertical">
          <div class="text-16px text-black font-600">
            支付信息
            <a-button v-permission="['shop:order:manage']" type="text" size="mini" :loading="refreshLoading" @click="refreshPayResult">
              <icon-refresh />
            </a-button>
          </div>
          <div class="flex-row-start-center">
            <span class="item-label">支付状态</span>
            <a-badge v-if="dataDetail?.payOff" status="success" text="已支付" />
            <a-badge v-else-if="dataDetail?.cancelTime" status="warning" text="已取消" />
            <a-space v-else>
              <a-badge status="normal" text="未支付" />
              <a-button v-permission="[' edu:enroll:verify']" type="primary" size="mini" @click="onOfflinePay">
                线下支付
              </a-button>
            </a-space>
          </div>
          <div v-if="!dataDetail?.cancelTime" class="flex-row-start-center">
            <span class="item-label">支付方式</span>
            <span class="item-value">
              {{ useDictLabel('PayTypeEnum', dataDetail?.payType) }}
            </span>
          </div>
          <div v-if="!dataDetail?.cancelTime" class="flex-row-start-center">
            <span class="item-label">支付时间</span>
            <span class="item-value">{{ dataDetail?.payTime || '-' }}</span>
          </div>
          <div v-if="dataDetail?.cancelTime" class="flex-row-start-center">
            <span class="item-label">取消时间</span>
            <span class="item-value">{{ dataDetail?.cancelTime || '-' }}</span>
          </div>
          <div v-if="!dataDetail?.cancelTime" class="flex-row-start-center">
            <span class="item-label">财务账户</span>
            <span class="item-value">
              {{ dataDetail?.finAccountName || '-' }}
            </span>
          </div>
        </a-space>
        <OfflinePayModal ref="OfflinePayModalRef" @success="onOfflinePaySuccess" />
      </div>
    </a-card>
  </ProPage>
</template>

<style lang='less' scoped>
:deep(.arco-page-header) {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #fff;
}
:deep(.arco-page-header-wrapper) {
  padding: 0;
}

:deep(.arco-form-item-label-col) {
  padding-right: 10px;
  width: 50px;
}

:deep(.pro-table-toolbar) {
  display: none;
}
.arco-divider {
  margin: 10px 0;
}
.label {
  display: inline-block;
  width: 80px;
  color: #888;
  flex-shrink: 0;
}
.value {
  color: #111;
}
.class-info {
  display: grid;
  grid-template-rows: repeat(4, 1fr);
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}
.lesson {
  :deep(.arco-card-body) {
    padding-top: 0 !important;
    background: #fff;
  }
}
:deep(.arco-card-body) {
  padding-top: 0 !important;
  background: #fff;
}

.active {
  border: 1px solid #fe840e;
  background: rgba(255, 125, 0, 0.1);
}

.order-info {
  padding: 20px;
  border-radius: 10px;
  background: #f5f7fd;

  .item-label {
    width: 88px;
    color: var(--text-3, #86909c);
  }
  .item-value {
    min-width: 100px;
    min-width: 100px;
    // color: var(--text-1, #1d2129);
  }
}

.tooltip-content {
  padding: 10px;
  background-color: var(--color-bg-popup);
  border-radius: 4px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.15);
}
</style>
